package oss

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha1"
	"duanju-mq/pkg/config"
	"encoding/base64"
	"errors"
	"net/http"
	"os"
	"strings"
	"time"
)

var (
	fAccessKeyId     = config.String("aliyun.oss.accesskey.id", "", "阿里云 OSS AccessKey ID")
	fAccessKeySecret = config.String("aliyun.oss.accesskey.secret", "", "阿里云 OSS AccessKey Secret")
	fEndpoint        = config.String("aliyun.oss.endpoint", "oss.aliyuncs.com", "阿里云 OSS API域名")
	fBucket          = config.String("aliyun.oss.bucket", "", "阿里云 OSS Bucket")
)

func SetAccessKey(id, secret string) {
	*fAccessKeyId = id
	*fAccessKeySecret = secret
}

func SetBucket(endpoint, bucket string) {
	*fEndpoint = endpoint
	*fBucket = bucket
}

func Upload(name, file string) error {
	b, err := os.ReadFile(file)
	if err != nil {
		return err
	}
	return UploadBytes(name, b)
}

func UploadBytes(name string, data []byte) error {
	// https://help.aliyun.com/document_detail/31951.html
	date := strings.ReplaceAll(time.Now().UTC().Format(time.RFC1123), "UTC", "GMT")
	sig := hmac_sha1("PUT\n\n\n" + date + "\n/" + *fBucket + "/" + name)
	req, err := http.NewRequest(http.MethodPut, "http://"+*fBucket+"."+*fEndpoint+"/"+name, bytes.NewReader(data))
	if err != nil {
		return err
	}
	req.Header.Add("Authorization", "OSS "+*fAccessKeyId+":"+sig)
	req.Header.Add("Date", date)

	client := &http.Client{Timeout: time.Minute}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusOK {
		return errors.New("http code err")
	}
	return nil
}

func hmac_sha1(s string) string {
	h := hmac.New(sha1.New, []byte(*fAccessKeySecret))
	h.Write([]byte(s))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
